/***********************************
 * @author David Buezas (david.buezas at gmail.com) Feel free to copy, modify and use the source as it fits you.
 * @modified Aksenov 14\06
 */

package ganga.custodian.plot;

import ganga.custodian.R;
import ganga.custodian.plot.SeekBarWithTwoThumb.SeekBarChangeListener;

import java.text.DecimalFormat;
import java.util.Vector;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.Shader;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.androidplot.ui.layout.AnchorPosition;
import com.androidplot.ui.layout.DynamicTableModel;
import com.androidplot.ui.layout.XLayoutStyle;
import com.androidplot.ui.layout.YLayoutStyle;
import com.androidplot.xy.BoundaryMode;
import com.androidplot.xy.LineAndPointFormatter;
import com.androidplot.xy.LineAndPointRenderer;
import com.androidplot.xy.XYPlot;
import com.androidplot.xy.XYStepMode;

public class PlotActivity extends Activity implements SeekBarChangeListener, OnTouchListener
    {
    private XYPlot mySimpleXYPlot;
    private ToggleButton bpmButton;
    private ToggleButton kigButton;
    private KIGSeries kigSeries;
    private BMPSeries bmpSeries;
    private BMPSeries dinamicPulse;
    final Vector<Double> dinamicVector = new Vector<Double> ();
    private LineAndPointFormatter colorKigSeries;
    private LineAndPointFormatter colorbmpSeries;
    private LineAndPointFormatter colordinamicPulse;
    private double minY;
    private double maxY;
    private double MINY;
    private double MAXY;
    private char selectSeries = 9; //1=KIG 0=BMP 9=NULL
    private double d1 [] = new double[]
        {600, 630, 660, 650, 610, 600, 610, 620, 610, 620, 630, 600, 630, 660, 650, 610, 600, 610, 620, 610, 620,
            630, 600, 630, 660, 650, 610, 600, 610, 620, 610, 620, 630, 600, 630, 660, 650, 610, 600, 610, 620, 610,
            620, 630, 600, 630, 660, 650, 610, 600, 610, 620, 610, 620, 630, 600, 630, 660, 650, 610, 600, 610, 620,
            610, 620, 630};
    private SeekBarWithTwoThumb seekBar;
    private  TextView textBegin, textEnd;

    //array to vector
    public Vector<Double> arrayToVector(double array []){
        Vector<Double> localVector = new Vector<Double> ();

        for (int i = 0; i < array.length; i++){
            double y = array[i];
            localVector.add(y);
            }
        return (localVector);
        }

    //part of array to vector
    public Vector<Double> partArrayToVector(double array [], int strt, int end){
        int i;
        Vector<Double> localVector = new Vector<Double> ();

        for (i = strt; i <= end; i++){
            double y = array[i];
            localVector.add(y);
            }
        return localVector;
        }

    public void bpmButton_Click(View v){
        if (selectSeries == 1){
            switchSeries();
            kigButton.setChecked(false);
            }

        else{
            bpmButton.setChecked(true);
            kigButton.setChecked(false);
            }
        }

    public void kigButton_Click(View v){
        if (selectSeries == 0){
            switchSeries();
            bpmButton.setChecked(false);
            }

        else{
            bpmButton.setChecked(false);
            kigButton.setChecked(true);
            }
        }

    public void dinUpdatePlot(double dinData){
        dinamicVector.add(dinData);
        mySimpleXYPlot.addSeries(dinamicPulse, LineAndPointRenderer.class, colordinamicPulse);
        mySimpleXYPlot.redraw();
        }

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.plot);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        bpmButton = (ToggleButton)findViewById(R.id.toggleButton1);
        kigButton = (ToggleButton)findViewById(R.id.toggleButton2);
        mySimpleXYPlot = (XYPlot)findViewById(R.id.mySimpleXYPlot);
        buildXYPlot(mySimpleXYPlot);
        kigSeries = new KIGSeries(arrayToVector(d1));
        bmpSeries = new BMPSeries(arrayToVector(d1));
        kigSeries.setLabel(getString(R.string.KIG));
        bmpSeries.setLabel(getString(R.string.BMP));
        
        dinamicPulse = new BMPSeries(dinamicVector);
        switchSeries();
        textBegin = (TextView)findViewById(R.id.textView1);
        textEnd = (TextView)findViewById(R.id.textView22);
        seekBar = (SeekBarWithTwoThumb)findViewById(R.id.myseekbar);
        seekBar.setSeekBarChangeListener(this);
        }

    public void SeekBarValueChanged(int Thumb1Value, int Thumb2Value){
    	textBegin.setText(getString(R.string.Begin) + ":" + Thumb1Value + " %");
    	textEnd.setText(getString(R.string.End) + ":" + Thumb2Value + " %");
        setDomainScaleValues(Thumb1Value, Thumb2Value);
        }

    private void setDomainScaleValues(int firstValue, int secondValue){
        int first = firstValue;
        int second = secondValue;
        int max;
        int min;

        if (first > second){
            max = first;
            min = second;
            }

        else{
            max = second;
            min = first;
            }
        minY = Math.round((bmpSeries.getMaxX() / 100 * min) / 100) * 100;
        maxY = Math.round((bmpSeries.getMaxX() / 100 * max) / 100) * 100;
        MAXY = Math.round((bmpSeries.getMaxX() / 100 * max) / 100) * 100;
        MINY = Math.round((bmpSeries.getMaxX() / 100 * min) / 100) * 100;
        checkBoundaries();
        }

    public void setScaleButton_Click(View v){
        }

    private PointF firstFinger;
    private float lastScrolling;
    private float lastZooming;

    public boolean onTouch(View arg0, MotionEvent event){
        switch (event.getAction() & MotionEvent.ACTION_MASK){
            case MotionEvent.ACTION_DOWN: // Start gesture
                firstFinger = new PointF(event.getX(), event.getY());

            case MotionEvent.ACTION_MOVE:
            {
                final PointF oldFirstFinger = firstFinger;
                firstFinger = new PointF(event.getX(), event.getY());
                lastScrolling = oldFirstFinger.x - firstFinger.x;
                lastZooming = (firstFinger.y - oldFirstFinger.y);
                zoom(lastZooming);
                scroll(lastScrolling);
                checkBoundaries();
                mySimpleXYPlot.redraw();
                }
            }

        return true;
        }
    private double shiftOnScale = 100;

    private void zoom(float scale){
        shiftOnScale = (Math.round((maxY - minY) / 10000) * 100);

        if (scale > 10){
            if (minY > MINY)
                minY -= shiftOnScale;

            if (maxY < MAXY)
                maxY += shiftOnScale;
            }

        if (scale < -10 && (maxY - minY > (Math.round(bmpSeries.getMaxX() / 1000) * 100) * 2)){
            minY += shiftOnScale;
            maxY -= shiftOnScale;
            }
        }

    private void scroll(float pan){
        shiftOnScale = (Math.round((maxY - minY) / 10000) * 100);

        if (pan > 10 && maxY < MAXY){
            minY += shiftOnScale;
            maxY += shiftOnScale;
            }

        if (pan < -10 && minY > MINY){
            minY -= shiftOnScale;
            maxY -= shiftOnScale;
            }
        }

    private void checkBoundaries(){
        mySimpleXYPlot.setDomainBoundaries(minY, maxY, BoundaryMode.AUTO);
        }

    private void buildXYPlot(XYPlot aSimpleXYPlot){
        aSimpleXYPlot.setOnTouchListener(this);

        aSimpleXYPlot.getGraphWidget().setTicksPerRangeLabel(2);
        aSimpleXYPlot.getGraphWidget().setTicksPerDomainLabel(5);
        aSimpleXYPlot.getGraphWidget().setRangeValueFormat(new DecimalFormat("#####"));
        aSimpleXYPlot.getGraphWidget().setDomainValueFormat(new DecimalFormat("#####"));
        aSimpleXYPlot.getGraphWidget().setRangeLabelWidth(25);
        aSimpleXYPlot.setDomainLabel(getString(R.string.TimeLabel));
        aSimpleXYPlot.disableAllMarkup();
        colorbmpSeries = new LineAndPointFormatter(Color.rgb(0, 155, 255), Color.rgb(80, 0, 255),
            Color.argb(150, 0, 0, 150));
        colorKigSeries = new LineAndPointFormatter(Color.rgb(255, 200, 0), Color.rgb(200, 255, 0),
            Color.argb(100, 0, 255, 100));
        colordinamicPulse = new LineAndPointFormatter(Color.rgb(0, 200, 0), Color.rgb(0, 255, 0),
            Color.argb(255, 255, 0, 100));
        Paint lineFill = new Paint();
        lineFill.setAlpha(400);
        lineFill.setShader(new LinearGradient(0, 0, 0, 250, Color.WHITE, Color.BLUE, Shader.TileMode.MIRROR));
        colorbmpSeries.setFillPaint(lineFill);
        Paint lineKigFill = new Paint();
        lineKigFill.setAlpha(400);
        lineKigFill.setShader(new LinearGradient(0, 0, 0, 250, Color.WHITE, Color.YELLOW, Shader.TileMode.MIRROR));
        colorKigSeries.setFillPaint(lineKigFill);
        Paint lineDinFill = new Paint();
        lineDinFill.setAlpha(400);
        lineDinFill.setShader(new LinearGradient(0, 0, 0, 250, Color.WHITE, Color.GREEN, Shader.TileMode.MIRROR));
        colordinamicPulse.setFillPaint(lineDinFill);
        minY = 0;
        MINY = 0;
        mySimpleXYPlot.getLegendWidget().setTableModel(new DynamicTableModel(1, 1));
        mySimpleXYPlot.position(mySimpleXYPlot.getDomainLabelWidget(), 190, XLayoutStyle.ABSOLUTE_FROM_RIGHT, -4,
            YLayoutStyle.ABSOLUTE_FROM_BOTTOM, AnchorPosition.RIGHT_BOTTOM);
        mySimpleXYPlot.position(mySimpleXYPlot.getLegendWidget(), -160, XLayoutStyle.ABSOLUTE_FROM_RIGHT, 203,
            YLayoutStyle.ABSOLUTE_FROM_BOTTOM, AnchorPosition.RIGHT_BOTTOM);
        }

    public void switchSeries(){
        if (selectSeries == 0){
            mySimpleXYPlot.removeSeries(bmpSeries, LineAndPointRenderer.class);
            mySimpleXYPlot.addSeries(kigSeries, LineAndPointRenderer.class, colorKigSeries);
            selectSeries = 1;
            mySimpleXYPlot.setDomainStep(XYStepMode.INCREMENT_BY_VAL, Math.round(kigSeries.getMaxX() / 1000) * 20);
            mySimpleXYPlot.setRangeStep(XYStepMode.INCREMENT_BY_VAL, 10);
            mySimpleXYPlot.setRangeLabel(getString(R.string.RRInterval));
            maxY = kigSeries.getMaxX();
            MAXY = kigSeries.getMaxX();
            // mySimpleXYPlot.setRangeBoundaries(kigSeries.getMinY()-5, kigSeries.getMaxY()+5, BoundaryMode.AUTO);
            mySimpleXYPlot.redraw();
            return;
            }

        else{
            if (selectSeries != 9)
                mySimpleXYPlot.removeSeries(kigSeries, LineAndPointRenderer.class);
            mySimpleXYPlot.addSeries(bmpSeries, LineAndPointRenderer.class, colorbmpSeries);
            selectSeries = 0;
            mySimpleXYPlot.setDomainStep(XYStepMode.INCREMENT_BY_VAL, Math.round(bmpSeries.getMaxX() / 1000) * 20);
            mySimpleXYPlot.setRangeStep(XYStepMode.INCREMENT_BY_VAL, 1);
            mySimpleXYPlot.setRangeLabel(getString(R.string.BeatsPerMinute));
            maxY = bmpSeries.getMaxX();
            MAXY = bmpSeries.getMaxX();
            // mySimpleXYPlot.setRangeBoundaries(bSeries.getMinY()-5, bSeries.getMaxY()+5, BoundaryMode.AUTO);
            mySimpleXYPlot.redraw();
            return;
            }
        }
    }